
from feature import Feature, FeatureParser, registerFeatureParserClass

class WiggleFeatureParser(FeatureParser):

    def __init__(self):
        self.step = 0
        self.pos = 0
        self.chr = None
        self.lastIndexContext = None
        
    def parse(self, line):
        # track type=wiggle_0 name="chr1:1-10000000" description="chr1:1-10000000--test
        # fixedStep chrom=chr1 start=148867 step=1
        if line == None or line.startswith("track"): return None
        if line.startswith("fixedStep"):
            self.setIndexContext(line.strip())
            return None
        feature = Feature(self.chr, self.pos, self.pos + self.step - 1, line)
        self.lastIndexContext = self.getIndexContext()
        self.pos += self.step
        return feature

    def getLastIndexContext(self):
        '''Return the context in which the most recently parsed feature was parsed.'''
        return self.lastIndexContext
    
    def getIndexContext(self):
        '''Return the context in which the next feature will be parsed.'''
        return "fixedStep chrom=%s start=%ld step=%ld" % (self.chr, self.pos, self.step)

    def setIndexContext(self, context):
        '''Parse the next feature in the specified context.'''
        fields = filter(lambda(x):x.find("=")>=0, context.strip().split(" "))
        for field in fields:
            (name, val) = field.split("=")
            val = val.replace("\"", "").replace("'", "")
            if name=="chrom":
                self.chr = val
            elif name=="start":
                self.pos = long(val)
            elif name=="step":
                self.step = long(val)
            else:
                raise Exception("couldn't parse fixedStep directive", line.strip())
    
    def getMaxFeatureSize(self):
        return 1

registerFeatureParserClass("wig", WiggleFeatureParser)
registerFeatureParserClass("phastcons.txt", WiggleFeatureParser)
